package com.xoa.service.party;


import com.xoa.dao.party.EnUnlicenseMapper;
import com.xoa.dao.party.MapOwnerinfoMapper;
import com.xoa.model.party.EnUnlicense;
import com.xoa.model.users.Users;
import com.xoa.util.DateFormat;
import com.xoa.util.ExcelUtil;
import com.xoa.util.GetAttachmentListUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 无证无照
 * Created by gsb on 2018/1/8.
 */
@Service
public class EnUnlicenseService {

    @Resource
    private EnUnlicenseMapper enUnlicenseMapper;
    @Resource
    private MapOwnerinfoMapper mapOwnerinfoMapper;
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-8 下午17:46:51
     * 类介绍  :   新建
     * 构造参数:
     *
     */
    public ToJson<EnUnlicense> insertSelective(EnUnlicense enUnlicense, HttpServletRequest request){
        ToJson<EnUnlicense> json = new ToJson<>();
        try {
            Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
            enUnlicense.setCreateUser(user.getUserId());
            enUnlicense.setCreateTime(DateFormat.getDatestr(new Date()));
            enUnlicenseMapper.insertSelective(enUnlicense);
            json.setFlag(0);
            json.setMsg("成功");
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-9 上午9:46:51
     * 类介绍  :   删除
     * 构造参数:
     *
     */
    public ToJson<EnUnlicense> deleteByPrimaryKey(Integer mid){
        ToJson<EnUnlicense> json = new ToJson<>();
        try {
            enUnlicenseMapper.deleteByPrimaryKey(mid);
            json.setFlag(0);
            json.setMsg("成功");
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-9 上午9:46:51
     * 类介绍  :   修改
     * 构造参数:
     *
     */
    public ToJson<EnUnlicense> updateByPrimaryKeySelective(EnUnlicense enUnlicense){
        ToJson<EnUnlicense> json = new ToJson<>();
        try {
            enUnlicenseMapper.updateByPrimaryKeySelective(enUnlicense);
            json.setFlag(0);
            json.setMsg("成功");
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-9 上午9:46:51
     * 类介绍  :   详情
     * 构造参数:
     *
     */
    public ToJson<EnUnlicense> selectById(Integer mid, HttpServletRequest request){
        ToJson<EnUnlicense> json = new ToJson<>();
        try {
            String sqlType = "xoa"
                    + (String) request.getSession().getAttribute("loginDateSouse");
            EnUnlicense enUnlicense = enUnlicenseMapper.selectById(mid);
            if (enUnlicense!=null){
                if (enUnlicense.getAttachmentName1() != null && enUnlicense.getAttachmentId1() != null) {
                    enUnlicense.setAttachments1(GetAttachmentListUtil.returnAttachment(enUnlicense.getAttachmentName1(), enUnlicense.getAttachmentId1(), sqlType, GetAttachmentListUtil.MODULE_parameter));
                }
                if (enUnlicense.getAttachmentName2() != null && enUnlicense.getAttachmentId2() != null) {
                    enUnlicense.setAttachments2(GetAttachmentListUtil.returnAttachment(enUnlicense.getAttachmentName2(), enUnlicense.getAttachmentId2(), sqlType, GetAttachmentListUtil.MODULE_parameter));
                }
            }
            json.setObject(enUnlicense);
            json.setFlag(0);
            json.setMsg("成功");

        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }


    public ToJson<EnUnlicense> queryByList(){
        ToJson<EnUnlicense> json = new ToJson<>();
        try {

            List<EnUnlicense> enUnlicense = enUnlicenseMapper.queryByList();


            json.setObject(enUnlicense);
            json.setFlag(0);
            json.setMsg("成功");

        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }




    public ToJson<EnUnlicense> selectByList(EnUnlicense enUnlicense, Integer page, Integer pageSize,
                                            boolean useFlag, HttpServletRequest request, HttpServletResponse response){
        ToJson<EnUnlicense> json = new ToJson<>();
        try {
            PageParams pageParams=new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            if(useFlag){
                map.put("page", pageParams);
            }
            map.put("gridLocation",enUnlicense.getGridLocation());

            List<EnUnlicense> enUnlicenseList = enUnlicenseMapper.selectByList(map);

            String jutiAddress=mapOwnerinfoMapper.selectByLabelName(enUnlicense.getGridLocation());

            enUnlicenseList.get(0).setJutiAddress(jutiAddress);

            if (enUnlicenseList!=null && enUnlicenseList.size()>0){
                for (EnUnlicense enUnlicense1 :enUnlicenseList){
                    if ("1".equals(enUnlicense1.getSitNature())){
                        enUnlicense1.setSitNature("异地经营");
                    }else  if ("2".equals(enUnlicense1.getSitNature())){
                        enUnlicense1.setSitNature("无证无照");
                    }else {
                        enUnlicense1.setSitNature("");
                    }
                }
            }
            json.setObj(enUnlicenseList);
            json.setTotleNum(enUnlicenseMapper.selectCount(enUnlicense));
            json.setFlag(0);
            json.setMsg("成功");
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }

    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-9 上午10:46:51
     * 类介绍  :   列表  查询  导出
     * 构造参数:
     *
     */
    public ToJson<EnUnlicense> queryList(EnUnlicense enUnlicense, Integer page, Integer pageSize,
                                         boolean useFlag, HttpServletRequest request, HttpServletResponse response, String export){
        ToJson<EnUnlicense> json = new ToJson<>();
        try {
            PageParams pageParams=new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            if(useFlag){
                map.put("page", pageParams);
            }
            map.put("enUnlicense",enUnlicense);
            if(export==null){
                export="0";
            }
            List<EnUnlicense> enUnlicenseList = enUnlicenseMapper.selectList(map);
            if (enUnlicenseList!=null && enUnlicenseList.size()>0){
                for (EnUnlicense enUnlicense1 :enUnlicenseList){
                    if ("1".equals(enUnlicense1.getSitNature())){
                        enUnlicense1.setSitNature("异地经营");
                    }else  if ("2".equals(enUnlicense1.getSitNature())){
                        enUnlicense1.setSitNature("无证无照");
                    }else {
                        enUnlicense1.setSitNature("");
                    }
                }
            }
            json.setObj(enUnlicenseList);
            json.setTotleNum(enUnlicenseMapper.selectCount(enUnlicense));
            json.setFlag(0);
            json.setMsg("成功");
            if (export.equals("1")){
                HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("无证无照信息", 22);
                String[] secondTitles = {"社区", "经营地址", "经营场所性质", "所属镇、街道", "姓名","身份证号",
                        "经营场所面积","牌匾、标识","经营者姓名","经营者身份证号","经营者籍贯","从业人数",
                        "经营项目", "经营者电话", "销账时间","街乡镇", "所属街路", "无证无照处置经营结果",
                        "本地人","外埠人", "涉及许可部门 ","销账原因 "};
                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
                String[] beanProperty = {"grid", "businessAddress", "sitNature", "townStreet", "name", "idNum",
                        "operateArea","plaque","operateName","operateId","operateNature","employNum",
                        "businessProject","operatePhone","chargeTime","streetVillageTown",
                        "streetRoad","result", "local","outsider", "m1","m2"};
                HSSFWorkbook workbook = null;
                workbook = ExcelUtil.exportExcelData(workbook2, enUnlicenseList, beanProperty);
                OutputStream out = response.getOutputStream();
                String filename = "无证无照信息记录表.xls";
                filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                response.setHeader("content-disposition", "attachment;filename=" + filename);
                workbook.write(out);
                out.close();

            }


        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-9 上午10:46:51
     * 类介绍  :   导入
     * 构造参数:
     *
     */
    public ToJson<EnUnlicense> importEnUnlicense(MultipartFile file, HttpServletResponse response,
                                                 HttpServletRequest request, HttpSession session) {
        ToJson<EnUnlicense> json = new ToJson<>();
        // 成功次数
        Integer successCount = 0;
        try {
            Users users= SessionUtils.getSessionInfo(request.getSession(), Users.class,new Users());

            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
            if (osName.toLowerCase().startsWith("win")) {
                path = path.append(rb.getString("upload.win"));
            } else {
                path = path.append(rb.getString("upload.linux"));
            }
            // 判断是否为空文件
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                json.setFlag(1);
                return json;
            }else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
//                    file.transferTo(dest);
                    // 将文件上传成功后进行读取文件
                    // 进行读取的路径
//                    String readPath = path.append(fileName).toString();
//                    String readPath = file.getInputStream();
                    InputStream in =  file.getInputStream();
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    EnUnlicense enUnlicense = null;
                    for (int i = 1; i <= lastRowNum; i++) {
                        enUnlicense = new EnUnlicense();
                        row = sheetObj.getRow(i);
                        String value = "";
                        if (row != null ) {
                            for (int j = 0; j < colNum; j++) {
                                Cell cell = row.getCell(j);
                                if (cell != null ) {
                                    switch (j) {
                                        case 0:
                                            //社区
                                            enUnlicense.setGrid(cell.getStringCellValue());
                                            break;
                                        case 1:
                                            //经营地址
                                            enUnlicense.setBusinessAddress(cell.getStringCellValue());
                                            break;
                                        case 2:
                                            //经营场所性质
                                            if ("异地经营".equals(cell.getStringCellValue().trim())){
                                                enUnlicense.setSitNature("1");
                                            }else if ("无证无照".equals(cell.getStringCellValue().trim())){
                                                enUnlicense.setSitNature("2");
                                            }else {
                                                enUnlicense.setSitNature("");
                                            }
                                            break;
                                        case 3:
                                            //所属镇、街道
                                            enUnlicense.setTownStreet(cell.getStringCellValue());
                                            break;
                                        case 4:
                                            //姓名
                                            enUnlicense.setName(cell.getStringCellValue());
                                            break;
                                        case 5:
                                            //身份证号
                                            if(cell.getCellType() == CellType.NUMERIC){
                                                cell.setCellType(CellType.STRING);
                                            }
                                            enUnlicense.setIdNum(cell.getStringCellValue());
                                            break;
                                        case 6:
                                            //经营场所面积
                                            if(cell.getCellType() == CellType.NUMERIC){
                                                cell.setCellType(CellType.STRING);
                                            }
                                            enUnlicense.setOperateArea(cell.getStringCellValue());
                                            break;
                                        case 7:
                                            //牌匾、标识
                                            enUnlicense.setPlaque(cell.getStringCellValue());
                                            break;
                                        case 8:
                                            //经营者姓名
                                            enUnlicense.setOperateName(cell.getStringCellValue());
                                            break;
                                        case 9:
                                            //经营者身份证号
                                            if(cell.getCellType() == CellType.NUMERIC){
                                                cell.setCellType(CellType.STRING);
                                            }
                                            enUnlicense.setOperateId(cell.getStringCellValue());
                                            break;
                                        case 10:
                                            //经营者籍贯
                                            enUnlicense.setOperateNature(cell.getStringCellValue());
                                            break;
                                        case 11:
                                            //从业人数
                                            if(cell.getCellType() == CellType.NUMERIC){
                                                cell.setCellType(CellType.STRING);
                                            }
                                            if (!cell.getStringCellValue().equals("")){
                                                enUnlicense.setEmployNum(Integer.parseInt(cell.getStringCellValue()));
                                            }
                                            break;
                                        case 12:
                                            //经营项目
                                            enUnlicense.setBusinessProject(cell.getStringCellValue());
                                            break;
                                        case 13:
                                            //经营者电话
                                            if(cell.getCellType() == CellType.NUMERIC){
                                                cell.setCellType(CellType.STRING);
                                            }
                                            enUnlicense.setOperatePhone(cell.getStringCellValue());
                                            break;
                                        case 14:
                                            //销账时间
                                            String result1 = null;
                                            if(cell.getCellType() == CellType.NUMERIC){
                                                short format = cell.getCellStyle().getDataFormat();
                                                SimpleDateFormat sdf = null;
                                                if(format == 14 || format == 31 || format == 57 || format == 58){
                                                    //日期
                                                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                                                }else if (format == 20 || format == 32) {
                                                    //时间
                                                    sdf = new SimpleDateFormat("HH:mm");
                                                }
                                                double v = cell.getNumericCellValue();
                                                Date dates = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
                                                result1 = sdf.format(dates);
                                               enUnlicense.setChargeTime(result1);
                                                break;
                                            }
                                            enUnlicense.setChargeTime(cell.getStringCellValue());
                                            break;
                                        case 15:
                                            //街乡镇
                                            enUnlicense.setStreetVillageTown(cell.getStringCellValue());
                                            break;
                                        case 16:
                                            //所属街路
                                            enUnlicense.setStreetRoad(cell.getStringCellValue());
                                            break;
                                        case 17:
                                            //无证无照处置经营结果
                                            enUnlicense.setResult(cell.getStringCellValue());
                                            break;
                                        case 18:
                                            //本地人
                                            if(cell.getCellType() == CellType.NUMERIC){
                                                cell.setCellType(CellType.STRING);
                                            }
                                            enUnlicense.setLocal(cell.getStringCellValue());
                                        case 19:
                                            //外埠人
                                            if(cell.getCellType() == CellType.NUMERIC){
                                                cell.setCellType(CellType.STRING);
                                            }
                                            enUnlicense.setOutsider(cell.getStringCellValue());
                                            break;
                                        case 20:
                                            //涉及许可部门
                                            enUnlicense.setM1(cell.getStringCellValue());
                                            break;
                                        case 21:
                                            //销账原因
                                            enUnlicense.setM2(cell.getStringCellValue());
                                            break;
                                        case 22:
                                            enUnlicense.setGridLocation(mapOwnerinfoMapper.selectCoordingbyName(cell.getStringCellValue()));
                                            break;
                                        default:
                                            json.setFlag(0);
                                            json.setMsg("err");
                                            break;
                                    }
                                }

                            }
                            enUnlicense.setCreateUser(users.getUserId());
                            enUnlicense.setCreateTime(DateFormat.getCurrentTime());
                            //将数据放入数据库
                            int count=enUnlicenseMapper.insertSelective(enUnlicense);
                            if(count>0) {
                                successCount = successCount + count;
                            }
                            dest.delete();
                        }
                    }

                }
            }
            if(successCount>0){
                json.setTotleNum(successCount);
                json.setMsg("ok");
                json.setFlag(0);
                return  json;
            }
        }catch (Exception e){
            e.printStackTrace();
            json.setTotleNum(successCount+1);
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }


    }
